import api from '@/api';

const state = {
  // 分销商信息
  distributorInfo: null,
  isDistributor: false,
  
  // 分销统计
  distributionStats: {
    totalGoods: 0,        // 分销商品数
    totalOrders: 0,        // 总订单数
    totalCommission: 0,     // 总佣金
    todayCommission: 0,     // 今日佣金
    monthCommission: 0,     // 本月佣金
    pendingCommission: 0,   // 待结算佣金
    teamSize: 0           // 团队人数
  },
  
  // 我的分销商品
  myDistributionGoods: [],
  
  // 佣金明细
  commissionList: [],
  
  // 团队成员
  teamMembers: [],
  
  // 推广数据
  promotionData: {
    clicks: 0,
    visits: 0,
    orders: 0,
    commission: 0
  }
};

const mutations = {
  // 设置分销商信息
  SET_DISTRIBUTOR_INFO(state, info) {
    state.distributorInfo = info;
    state.isDistributor = !!info;
    uni.setStorageSync('distributorInfo', info);
  },
  
  // 设置分销统计
  SET_DISTRIBUTION_STATS(state, stats) {
    state.distributionStats = { ...state.distributionStats, ...stats };
  },
  
  // 设置我的分销商品
  SET_MY_DISTRIBUTION_GOODS(state, goods) {
    state.myDistributionGoods = goods;
  },
  
  // 添加分销商品
  ADD_DISTRIBUTION_GOOD(state, goods) {
    state.myDistributionGoods.unshift(goods);
  },
  
  // 移除分销商品
  REMOVE_DISTRIBUTION_GOOD(state, goodsId) {
    const index = state.myDistributionGoods.findIndex(item => item.id === goodsId);
    if (index > -1) {
      state.myDistributionGoods.splice(index, 1);
    }
  },
  
  // 设置佣金明细
  SET_COMMISSION_LIST(state, list) {
    state.commissionList = list;
  },
  
  // 添加佣金记录
  ADD_COMMISSION_RECORD(state, record) {
    state.commissionList.unshift(record);
  },
  
  // 设置团队成员
  SET_TEAM_MEMBERS(state, members) {
    state.teamMembers = members;
  },
  
  // 添加团队成员
  ADD_TEAM_MEMBER(state, member) {
    state.teamMembers.unshift(member);
    state.distributionStats.teamSize++;
  },
  
  // 设置推广数据
  SET_PROMOTION_DATA(state, data) {
    state.promotionData = { ...state.promotionData, ...data };
  },
  
  // 更新推广点击数
  UPDATE_CLICKS(state) {
    state.promotionData.clicks++;
  },
  
  // 清除分销状态
  CLEAR_DISTRIBUTION_STATE(state) {
    state.distributorInfo = null;
    state.isDistributor = false;
    state.distributionStats = {
      totalGoods: 0,
      totalOrders: 0,
      totalCommission: 0,
      todayCommission: 0,
      monthCommission: 0,
      pendingCommission: 0,
      teamSize: 0
    };
    state.myDistributionGoods = [];
    state.commissionList = [];
    state.teamMembers = [];
    state.promotionData = {
      clicks: 0,
      visits: 0,
      orders: 0,
      commission: 0
    };
    
    uni.removeStorageSync('distributorInfo');
  }
};

const actions = {
  // 成为分销商
  async becomeDistributor({ commit }) {
    try {
      const response = await api.distribution.becomeDistributor();
      commit('SET_DISTRIBUTOR_INFO', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('成为分销商失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 获取分销商信息
  async getDistributorInfo({ commit }) {
    try {
      const response = await api.distribution.getDistributorInfo();
      commit('SET_DISTRIBUTOR_INFO', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取分销商信息失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 获取分销统计
  async getDistributionStats({ commit }) {
    try {
      const response = await api.distribution.getStats();
      commit('SET_DISTRIBUTION_STATS', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取分销统计失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 获取我的分销商品
  async getMyDistributionGoods({ commit }) {
    try {
      const response = await api.distribution.getMyGoods();
      commit('SET_MY_DISTRIBUTION_GOODS', response.data.list);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取分销商品失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 添加分销商品
  async addDistributionGood({ commit }, goodsId) {
    try {
      const response = await api.distribution.addGoods({ goods_id: goodsId });
      commit('ADD_DISTRIBUTION_GOOD', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('添加分销商品失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 移除分销商品
  async removeDistributionGood({ commit }, goodsId) {
    try {
      const response = await api.distribution.removeGoods({ goods_id: goodsId });
      commit('REMOVE_DISTRIBUTION_GOOD', goodsId);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('移除分销商品失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 获取佣金明细
  async getCommissionList({ commit }, params = {}) {
    try {
      const response = await api.distribution.getCommissionList(params);
      commit('SET_COMMISSION_LIST', response.data.list);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取佣金明细失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 获取团队成员
  async getTeamMembers({ commit }) {
    try {
      const response = await api.distribution.getTeamMembers();
      commit('SET_TEAM_MEMBERS', response.data.list);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取团队成员失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 邀请成员
  async inviteMember({ commit }, inviteInfo) {
    try {
      const response = await api.distribution.inviteMember(inviteInfo);
      commit('ADD_TEAM_MEMBER', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('邀请成员失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 获取推广数据
  async getPromotionData({ commit }) {
    try {
      const response = await api.distribution.getPromotionData();
      commit('SET_PROMOTION_DATA', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取推广数据失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 记录推广点击
  recordPromotionClick({ commit }, data) {
    try {
      api.distribution.recordClick(data);
      commit('UPDATE_CLICKS');
    } catch (error) {
      console.error('记录推广点击失败:', error);
    }
  },
  
  // 申请提现
  async withdraw(_, { amount, type = 'wechat' }) {
    try {
      const response = await api.distribution.withdraw({ amount, type });
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('申请提现失败:', error);
      return { success: false, error: error.message };
    }
  }
};

const getters = {
  // 是否为分销商
  isDistributor: state => state.isDistributor,
  
  // 分销商信息
  distributorInfo: state => state.distributorInfo,
  
  // 分销统计
  distributionStats: state => state.distributionStats,
  
  // 我的分销商品
  myDistributionGoods: state => state.myDistributionGoods,
  
  // 佣金明细
  commissionList: state => state.commissionList,
  
  // 团队成员
  teamMembers: state => state.teamMembers,
  
  // 推广数据
  promotionData: state => state.promotionData,
  
  // 总佣金收益
  totalCommission: state => state.distributionStats.totalCommission,
  
  // 今日佣金
  todayCommission: state => state.distributionStats.todayCommission,
  
  // 可提现余额
  availableBalance: state => {
    const settled = state.distributionStats.totalCommission;
    const pending = state.distributionStats.pendingCommission;
    return settled - pending;
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};